import {prodConfig} from '../config.js';
import shell from 'shelljs';
import Client from 'ssh2-sftp-client';

import path from 'path';

import { fileURLToPath } from 'url';

const __filenameNew = fileURLToPath(import.meta.url);

const __dirnameNew = path.dirname(__filenameNew);
// 打包 npm run build
const compileDist = async() => {
	if (shell.exec('pnpm build').code === 0) {
		console.log('打包成功');
	}
};

async function connectSSh() {
	const sftp = new Client();
	sftp.connect({
		host: prodConfig.ip, // 服务器 IP
		port: prodConfig.port,
		username: prodConfig.username,
		password: prodConfig.password
	}).then(() => {
		console.log('先执行删除服务器文件');
		return sftp.rmdir(prodConfig.rmpath, true);
	}).then(() => {
		// 上传文件
		console.log('删除成功，开始上传');
		return sftp.uploadDir(path.resolve(__dirnameNew, '../../dist'), prodConfig.path);
	}).then(() => {
		console.log('上传完成,开始拷贝至运行目录');
	}).catch((err) => {
		console.log(err, '失败');
	}).finally(() => {
		sftp.end();
		console.log('部署成功');
	});
}
async function runTask() {
	await compileDist(); // 打包完成
	await connectSSh(); // 提交上传至个人目录
}
runTask();